package com.org.javabody.Java_To_Json.BuildJson;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

public class BaseBuildJson {

	 public void buildJson() {
	    	//HashMap构造


	    	JSONObject jObj = new JSONObject();
	    	Map<String, String> map = new HashMap <String, String>();
	    	map.put("rowid", "1000");
	    	map.put("name", "甘恒旭");
	    	map.put("sex", "男");
	    	map.put("birth", "1992-11-13");
	    	System.out.print("①先把值放到Map中:");
	    	System.out.println(map);
	    	System.out.print("②再把值put到json类中:");
	    	jObj.put("甘恒旭基本信息", map);
	    	System.out.println(jObj);
	    	System.out.print("③解析刚才的Json:");
	    	System.out.println(jObj.getString("甘恒旭基本信息"));
	    	
	    	JSONObject jsonObj2 = new JSONObject().fromObject(jObj.getString("甘恒旭基本信息"));
	    	String parse = null;
	    	try {
	    		 parse = jsonObj2.getString("1000");
	    	} catch (Exception e) {//可以忽视异常(已捕获但忽视)，让前台不报错

	    		//System.out.println("解析异常："+e);//也可以捕获异常，让前台显示异常信息


	    	}
	    	
	    	if(parse!=null) {
	    		System.out.println(jsonObj2.getString("1000"));
	    	}
	    	System.out.print("④获取JSON里面的name的值：");
	    	System.out.println(jsonObj2.getString("name"));
	    	System.out.println("⑤Json转回Map：");
	    	Map<String, Object> map2 = (Map) JSONObject.toBean(JSONObject
	    	         .fromObject(jsonObj2), Map.class);
	    	  for (Entry<String, Object> entry : map2.entrySet()) {   //json转回map

	    	         System.out.print(entry.getKey() + "=" + entry.getValue());
	    	         System.out.print("\n");
	    	        }
	    }
		public static void main(String[] args) {
			BaseBuildJson json = new BaseBuildJson();
			json.buildJson();
		}

}